package fr.resasante.utils;

import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.naming.NamingException;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import fr.resasante.exception.ApplicationException;

/**
 * Class for getting agreements in XML
 * 
 * @author GEFFROY-DE-VILLEBLAN
 * 
 */
public final class AgreementsUtils {
	/**
	 * Properties class instance
	 */
	private static volatile AgreementsUtils instance = null;

	/**
	 * Agreement list
	 */
	private Element root;

	/**
	 * Constructor
	 */
	private AgreementsUtils() {
		super();
		loadXmlFile();
	}

	/**
	 * Method returning a Singleton class instance
	 * 
	 * @return Singleton instance
	 * @throws NamingException
	 */
	public final static AgreementsUtils getInstance() {
		if (AgreementsUtils.instance == null) {
			synchronized (AgreementsUtils.class) {
				if (AgreementsUtils.instance == null) {
					AgreementsUtils.instance = new AgreementsUtils();
				}
			}
		}
		return AgreementsUtils.instance;
	}

	/**
	 * Load the XML file
	 */
	private void loadXmlFile() {
		try {
			InputStream xmlStream = this.getClass().getClassLoader()
					.getResourceAsStream("agreements.xml");
			SAXReader reader = new SAXReader();
			Document doc = reader.read(xmlStream);
			root = doc.getRootElement();
		} catch (Exception e) {
			throw new ApplicationException("Unable to find the XML file agreements.xml", e);
		}
	}

	/**
	 * Get a list of agreements
	 * 
	 * @return The list of titles
	 */
	public Map<String, String> getAllAgreements() {
		Map<String, String> agreements = new LinkedHashMap<String, String>();

		@SuppressWarnings("rawtypes")
		Iterator iterator = root.elementIterator("agreement");
		while (iterator.hasNext()) {
			Element agreement = (Element) iterator.next();
			String code = agreement.elementText("code");
			String label = agreement.elementText("label");
			agreements.put(code, label);
		}
		return agreements;
	}
}